package com.sesample.seandroidsample;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

/**
 * Parse the xml file for product definitions
 */
public class CatalogueParser {

  public ArrayList<Product> parse(InputStream in) throws XmlPullParserException, IOException {
    ArrayList<Product> result = null;
    try {
      XmlPullParser parser = Xml.newPullParser();
      parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
      parser.setInput(in, null);

      result = parseProduct(parser);

    } catch (XmlPullParserException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }

  private ArrayList<Product> parseProduct(XmlPullParser parser) throws IOException, XmlPullParserException {

    ArrayList<Product> products = new ArrayList<Product>();
    int eventType = parser.getEventType();

    Product current = null;
    int productId = 0;
    String productName = "";
    float productPrice = 0;
    String productCategory = "";
    String productDescription = "";

    while (eventType != XmlPullParser.END_DOCUMENT) {
      String name = null;
      switch (eventType) {
      case XmlPullParser.START_TAG:
        name =parser.getName();
        if (name.equalsIgnoreCase("product")) {
          // Starting of a new product
        } else if (name.equalsIgnoreCase("id")) {
          productId = Integer.parseInt(parser.nextText());
        } else if (name.equalsIgnoreCase("name")) {
          productName = parser.nextText();
        } else if (name.equalsIgnoreCase("price")) {
          productPrice = Float.parseFloat(parser.nextText());
        } else if (name.equalsIgnoreCase("category")) {
          productCategory = parser.nextText();
        } else if (name.equalsIgnoreCase("description")){
          productDescription = parser.nextText();
        }
        break;
      case XmlPullParser.END_TAG:
        name = parser.getName();
        if (name.equalsIgnoreCase("product")) {
          // Done with one product
          current = new Product(
              productId,
              productName,
              productPrice,
              productCategory,
              productDescription
              );

          if (null != current) {
            Log.d("InventoryParser", "Loaded product: " + productId);
            products.add(current);
          }
        }
        break;
      }
      eventType = parser.next();
    }
    return products;
  }
}
